import { app } from 'electron'
import { join } from 'path'
import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs'

/**
 * 用户设置接口
 */
export interface UserSettings {
  // 窗口设置
  window: {
    width: number
    height: number
    x?: number
    y?: number
    isMaximized: boolean
    isAlwaysOnTop: boolean
  }
  
  // 应用设置
  app: {
    lastOpenFolder?: string
    theme: 'light' | 'dark' | 'auto'
    language: string
    autoStart: boolean
    minimizeToTray: boolean
    closeToTray: boolean
  }
  
  // 文件管理设置
  fileManager: {
    viewMode: 'grid' | 'list'
    sortBy: 'name' | 'size' | 'date' | 'type'
    sortOrder: 'asc' | 'desc'
    showHiddenFiles: boolean
  }
  
  // AI设置
  ai: {
    apiKey?: string
    selectedModel?: string
    autoSave: boolean
  }
}

/**
 * 默认设置
 */
const defaultSettings: UserSettings = {
  window: {
    width: 1200,
    height: 800,
    isMaximized: false,
    isAlwaysOnTop: false
  },
  app: {
    theme: 'auto',
    language: 'zh-CN',
    autoStart: false,
    minimizeToTray: true,
    closeToTray: true
  },
  fileManager: {
    viewMode: 'grid',
    sortBy: 'name',
    sortOrder: 'asc',
    showHiddenFiles: false
  },
  ai: {
    autoSave: true
  }
}

/**
 * 设置管理器
 */
export class SettingsManager {
  private settingsPath: string
  private settings: UserSettings

  constructor() {
    // 设置文件路径
    const userDataPath = app.getPath('userData')
    this.settingsPath = join(userDataPath, 'settings.json')
    
    // 确保目录存在
    if (!existsSync(userDataPath)) {
      mkdirSync(userDataPath, { recursive: true })
    }
    
    // 加载设置
    this.settings = this.loadSettings()
  }

  /**
   * 加载设置
   */
  private loadSettings(): UserSettings {
    try {
      if (existsSync(this.settingsPath)) {
        const data = readFileSync(this.settingsPath, 'utf-8')
        const loadedSettings = JSON.parse(data)
        
        // 合并默认设置和加载的设置
        return this.mergeSettings(defaultSettings, loadedSettings)
      }
    } catch (error) {
      console.error('加载设置失败:', error)
    }
    
    return { ...defaultSettings }
  }

  /**
   * 保存设置
   */
  private saveSettings(): void {
    try {
      writeFileSync(this.settingsPath, JSON.stringify(this.settings, null, 2), 'utf-8')
      console.log('设置已保存:', this.settingsPath)
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  }

  /**
   * 合并设置（深度合并）
   */
  private mergeSettings(defaults: any, loaded: any): any {
    const result = { ...defaults }
    
    for (const key in loaded) {
      if (loaded[key] && typeof loaded[key] === 'object' && !Array.isArray(loaded[key])) {
        result[key] = this.mergeSettings(defaults[key] || {}, loaded[key])
      } else {
        result[key] = loaded[key]
      }
    }
    
    return result
  }

  /**
   * 获取所有设置
   */
  getSettings(): UserSettings {
    return { ...this.settings }
  }

  /**
   * 获取窗口设置
   */
  getWindowSettings() {
    return { ...this.settings.window }
  }

  /**
   * 更新窗口设置
   */
  updateWindowSettings(windowSettings: Partial<UserSettings['window']>): void {
    this.settings.window = { ...this.settings.window, ...windowSettings }
    this.saveSettings()
  }

  /**
   * 获取应用设置
   */
  getAppSettings() {
    return { ...this.settings.app }
  }

  /**
   * 更新应用设置
   */
  updateAppSettings(appSettings: Partial<UserSettings['app']>): void {
    this.settings.app = { ...this.settings.app, ...appSettings }
    this.saveSettings()
  }

  /**
   * 获取文件管理设置
   */
  getFileManagerSettings() {
    return { ...this.settings.fileManager }
  }

  /**
   * 更新文件管理设置
   */
  updateFileManagerSettings(fileManagerSettings: Partial<UserSettings['fileManager']>): void {
    this.settings.fileManager = { ...this.settings.fileManager, ...fileManagerSettings }
    this.saveSettings()
  }

  /**
   * 获取AI设置
   */
  getAISettings() {
    return { ...this.settings.ai }
  }

  /**
   * 更新AI设置
   */
  updateAISettings(aiSettings: Partial<UserSettings['ai']>): void {
    this.settings.ai = { ...this.settings.ai, ...aiSettings }
    this.saveSettings()
  }

  /**
   * 重置所有设置
   */
  resetSettings(): void {
    this.settings = { ...defaultSettings }
    this.saveSettings()
  }

  /**
   * 导出设置
   */
  exportSettings(): string {
    return JSON.stringify(this.settings, null, 2)
  }

  /**
   * 导入设置
   */
  importSettings(settingsJson: string): boolean {
    try {
      const importedSettings = JSON.parse(settingsJson)
      this.settings = this.mergeSettings(defaultSettings, importedSettings)
      this.saveSettings()
      return true
    } catch (error) {
      console.error('导入设置失败:', error)
      return false
    }
  }
}

// 导出单例实例
export const settingsManager = new SettingsManager()
